<div class="tmd-doc">
<h1 class="tmd-header-1">
Code Blocks and Identifier Scopes
</h1>
<p></p>
<div class="tmd-usual">
This article will explain the code blocks and identifier scopes in Go.
</div>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(Please note, the definitions of code block hierarchies in this article are a little different from the viewpoint of <code class="tmd-code-span">go/*</code> standard packages.)</span>
</div>
<p></p>
<p></p>
<h3 id="block" class="tmd-header-3">
Code Blocks
</h3>
<p></p>
<div class="tmd-usual">
In a Go project, there are four kinds of code blocks (also called blocks later):
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
the <span class="tmd-bold">universe block</span> contains all project source code.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
each package has a <span class="tmd-bold">package block</span> containing all source code, excluding the package import declarations in that package.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
each file has a <span class="tmd-bold">file block</span> containing all the source code, including the package import declarations, in that file.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
generally, a pair of braces <code class="tmd-code-span">{}</code> encloses a <span class="tmd-bold">local block</span>. However, some local blocks aren't enclosed within <code class="tmd-code-span">{}</code>, such blocks are called implicit local blocks. The local blocks enclosed in <code class="tmd-code-span">{}</code> are called explicit local blocks. The <code class="tmd-code-span">{}</code> in composite literals and type definitions don't form local blocks.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
Some keywords in all kinds of control flows are followed by some implicit code blocks.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
An <code class="tmd-code-span">if</code>, <code class="tmd-code-span">switch</code> or <code class="tmd-code-span">for</code> keyword is followed by two nested local blocks. One is implicit, the other is explicit. The explicit one is nested in the implicit one. If such a keyword is followed by a short variable declaration, then the variables are declared in the implicit block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
An <code class="tmd-code-span">else</code> keyword is followed by one explicit or implicit block, which is nested in the implicit block following its <code class="tmd-code-span">if</code> counterpart keyword. If the <code class="tmd-code-span">else</code> keyword is followed by another <code class="tmd-code-span">if</code> keyword, then the code block following the <code class="tmd-code-span">else</code> keyword can be implicit, otherwise, the code block must be explicit.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
An <code class="tmd-code-span">select</code> keyword is followed by one explicit block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Each <code class="tmd-code-span">case</code> and <code class="tmd-code-span">default</code> keyword is followed by one implicit block, which is nested in the explicit block following its corresponding <code class="tmd-code-span">switch</code> or <code class="tmd-code-span">select</code> keyword.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
The local blocks which aren't nested in any other local blocks are called top-level (or package-level) local blocks. Top-level local blocks are all function bodies.
</div>
<p></p>
<div class="tmd-usual">
Note, the input parameters and output results of a function are viewed as being declared in explicit body code block of the function, even if their declarations stay out of the pair of braces enclosing the function body block.
</div>
<p></p>
<div class="tmd-usual">
Code block hierarchies:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
package blocks are nested in the universe block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
file blocks are also directly nested in the universe block, instead of package blocks. (This explanation is different from the <code class="tmd-code-span">go/*</code> standard packages.)
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
each top-level local block is nested in both a package block and a file block. (This explanation is also different from the <code class="tmd-code-span">go/*</code> standard packages.)
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
a non-top local block must be nested in another local block.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(The differences to Go specification are to make the below explanations for identifier shadowing simpler.)</span>
</div>
<p></p>
<div class="tmd-usual">
Here is a picture shows the block hierarchies in a program:
</div>
<p></p>
<div class="tmd-base tmd-align-center">
<div class="tmd-usual">
<img src="res/blocks.png" class="tmd-media"/>
</div>
</div>
<p></p>
<div class="tmd-usual">
Code blocks are mainly used to explain allowed declaration positions and scopes of source code element identifiers.
</div>
<p></p>
<h3 id="declaration" class="tmd-header-3">
Source Code Element Declaration Places
</h3>
<p></p>
<div class="tmd-usual">
There are six kinds of source code elements which can be declared:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
package imports.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
defined types and type alias.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
named constants.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
variables.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
functions.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
labels.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
Labels are used in the <code class="tmd-code-span">break</code>, <code class="tmd-code-span">continue</code>, and <code class="tmd-code-span">goto</code> statements.
</div>
<p></p>
<div class="tmd-usual">
A declaration binds a non-blank identifier to a source code element (constant, type, variable, function, label, or package). In other words, in the declaration, the declared source code element is named as the non-blank identifier. After the declaration, we can use the non-blank identifier to represent the declared source code element.
</div>
<p></p>
<div class="tmd-usual">
The following table shows which code blocks all kinds of source code elements can be directly declared in:
</div>
<table class="tmd-table">
<tr>
<th>

</th>
<th>
the universe block
</th>
<th>
package blocks
</th>
<th>
file blocks
</th>
<th>
local blocks
</th>
</tr>
<tr>
<th>
predeclared (built-in elements) <sup>(1)</sup>
</th>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
</tr>
<tr>
<th>
package imports
</th>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
</tr>
<tr>
<th>
defined types and type alias (non-builtin)
</th>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
</tr>
<tr>
<th>
named constants (non-builtin)
</th>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
</tr>
<tr>
<th>
variables (non-builtin) <sup>(2)</sup>
</th>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
</tr>
<tr>
<th>
functions (non-builtin)
</th>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
</tr>
<tr>
<th>
variables (non-builtin) <sup>(2)</sup>
</th>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<p />
<div class="tmd-usual">

</div>
</td>
<td>
<div class="tmd-usual">
Yes
</div>
</td>
</tr>
</table>
<p></p>
<div class="tmd-usual">
<sup>(1)</sup> predeclared elements are documented in <a href="https://golang.org/pkg/builtin/"><code class="tmd-code-span">builtin</code> standard package</a>.<br/><sup>(2)</sup> excluding struct field variables.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
So,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
package imports can never be declared in package blocks and local blocks.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
functions can never be declared in local blocks. (Anonymous functions can be enclosed in local blocks but they are not declarations.)
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
labels can only be declared in local blocks.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
Please note,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if the innermost containing blocks of two code element declarations are the same one, then the names (identifiers) of the two code elements can't be identical.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
the name (identifier) of a package-level code element declared in a package must not be identical to any package import name declared in any source file in the package (a.k.a., a package import name in a package must not be identical to any package-level code element declared in the package). This rule might <a href="https://github.com/golang/go/issues/7429">be relaxed later</a>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if the innermost containing function body blocks of two label declarations are the same one, then the names (identifiers) of the two labels can't be identical.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
the references of a label must be within the innermost function body block containing the declaration of the label.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
some special portions in the implicit local blocks in all kinds of control flows have special requirements. Generally, no code elements are allowed to be directly declared in such implicit local blocks, except some short variable declarations.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Each <code class="tmd-code-span">if</code>, <code class="tmd-code-span">switch</code> or <code class="tmd-code-span">for</code> keyword can be closely followed by a short variable declaration.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Each <code class="tmd-code-span">case</code> keyword in a <code class="tmd-code-span">select</code> control flow can be closely followed by a short variable declaration.
</div>
</li>
</ul>
</li>
</ul>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(BTW, the <code class="tmd-code-span">go/*</code> standard packages think file code blocks can only contain package import declarations.)</span>
</div>
<p></p>
<div class="tmd-usual">
The source code elements declared in package blocks but outside of any local blocks are called package-level source code elements. Package-level source code elements can be named constants, variables, functions, defined types, or type aliases.
</div>
<p></p>
<h3 id="scope" class="tmd-header-3">
Scopes of Declared Source Code Elements
</h3>
<p></p>
<p></p>
<div class="tmd-usual">
The scope of a declared identifier means the identifiable range of the identifier (or visible range).
</div>
<p></p>
<div class="tmd-usual">
Without considering identifier shadowing which will be explained in the last section of the current article, <a href="https://golang.org/ref/spec#Declarations_and_scope">the scope definitions</a> for the identifiers of all kinds of source code elements are listed below.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of a predeclared/built-in identifier is the universe block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of the identifier of a package import is the file block containing the package import declaration.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at package level is the package block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of an identifier denoting a method receiver, function parameter, or result variable is the corresponding function body (a local block).
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of the identifier of a constant or a variable declared inside a function body begins at the end of the specification of the constant or variable (or the end of the declaration for a short declared variable) and ends at the end of the innermost containing block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of the identifier of a type or a type alias declared inside a function body begins at the end of the identifier in the corresponding type specification and ends at the end of the innermost containing block.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The scope of a label is the body of the innermost function body block containing the label declaration but excludes all the bodies of anonymous functions nested in the containing function.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
About the scopes of type parameters, please read the <a href="https://go101.org/generics/555-type-constraints-and-parameters.html#type-parameter-scope">Go generics 101</a> book.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
Blank identifiers have no scopes.
</div>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(Note, the predeclared <code class="tmd-code-span">iota</code> is only visible in constant declarations.)</span>
</div>
<p></p>
<div id="scope-difference-detail" class="tmd-usual">
You may have noticed the minor difference of identifier scope definitions between local type definitions and local variables, local constants and local type aliases. The difference means a defined type may be able to reference itself in its declaration. Here is an example to show the difference.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

func main() {
	// var v int = v   // error: v is undefined
	// const C int = C // error: C is undefined
	/*
	type T = struct {
		*T    // error: T uses &lt;T&gt;
		x []T // error: T uses &lt;T&gt;
	}
	*/

	// Following type definitions are all valid.
	type T struct {
		*T
		x []T
	}
	type A [5]*A
	type S []S
	type M map[int]M
	type F func(F) F
	type Ch chan Ch
	type P *P

	// ...
	var p P
	p = &amp;p
	p = ***********************p
	***********************p = p

	var s = make(S, 3)
	s[0] = s
	s = s[0][0][0][0][0][0][0][0]

	var m = M{}
	m[1] = m
	m = m[1][1][1][1][1][1][1][1]
}
</code></pre>
<p></p>
<div class="tmd-usual">
Note, call <code class="tmd-code-span">fmt.Print(s)</code> and call <code class="tmd-code-span">fmt.Print(m)</code> both panic (for stack overflow).
</div>
<p></p>
<div class="tmd-usual">
And the scope difference between package-level and local declarations:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

// Here the two identifiers at each line are the
// same one. The right ones are both not the
// predeclared identifiers. Instead, they are
// same as respective left one. So the two
// lines both fail to compile.
/*
const iota = iota // error: constant definition loop
var true = true   // error: typechecking loop
*/

var a = b // can reference variables declared later
var b = 123

func main() {
	// The identifiers at the right side in the
	// next two lines are the predeclared ones.
	const iota = iota // ok
	var true = true   // ok
	_ = true

	// The following lines fail to compile, for
	// c references a later declared variable d.
	/*
	var c = d
	var d = 123
	_ = c
	*/
}
</code></pre>
<p></p>
<h3 id="shadow" class="tmd-header-3">
Identifier Shadowing
</h3>
<p></p>
<div class="tmd-usual">
Ignoring labels, an identifier declared in an outer code block can be shadowed by the same identifier declared in code blocks nested (directly or indirectly) in the outer code block.
</div>
<p></p>
<div class="tmd-usual">
Labels can’t be shadowed.
</div>
<p></p>
<div class="tmd-usual">
If an identifier is shadowed, its scope will exclude the scopes of its shadowing identifiers.
</div>
<p></p>
<div class="tmd-usual">
Below is an interesting example. The code contains 6 declared variables named <code class="tmd-code-span">x</code>. A <code class="tmd-code-span">x</code> declared in a deeper block shadows the <code class="tmd-code-span">x</code>s declared in shallower blocks.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

var p0, p1, p2, p3, p4, p5 *int
var x = 9999 // x#0

func main() {
	p0 = &amp;x
	var x = 888  // x#1
	p1 = &amp;x
	for x := 70; x &lt; 77; x++ {  // x#2
		p2 = &amp;x
		x := x - 70 //  // x#3
		p3 = &amp;x
		if x := x - 3; x &gt; 0 { // x#4
			p4 = &amp;x
			x := -x // x#5
			p5 = &amp;x
		}
	}

	// 9999 888 77 6 3 -3
	fmt.Println(*p0, *p1, *p2, *p3, *p4, *p5)
}
</code></pre>
<p></p>
<div class="tmd-usual">
Another example: the following program prints <code class="tmd-code-span">Sheep Goat</code> instead of <code class="tmd-code-span">Sheep Sheep</code>. Please read the comments for explanations.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

var f = func(b bool) {
	fmt.Print("Goat")
}

func main() {
	var f = func(b bool) {
		fmt.Print("Sheep")
		if b {
			fmt.Print(" ")
			f(!b) // The f is the package-level f.
		}
	}
	f(true) // The f is the local f.
}
</code></pre>
<p></p>
<div class="tmd-usual">
If we modify the above program as the following shown, then it will print <code class="tmd-code-span">Sheep Sheep</code>.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">func main() {
	var f func(b bool)
	f = func(b bool) {
		fmt.Print("Sheep")
		if b {
			fmt.Print(" ")
			f(!b) // The f is also the local f now.
		}
	}
	f(true)
}
</code></pre>
<p></p>
<div class="tmd-usual">
For some circumstances, when identifiers are shadowed by variables declared with short variable declarations, some new gophers may get confused about whether a variable in a short variable declaration is redeclared or newly declared. The following example (which has bugs) shows the famous trap in Go. Almost every gopher has ever fallen into the trap in the early days of using Go.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"
import "strconv"

func parseInt(s string) (int, error) {
	n, err := strconv.Atoi(s)
	if err != nil {
		// Some new gophers may think err is an
		// already declared variable in the following
		// short variable declaration. However, both
		// b and err are new declared here actually.
		// The new declared err variable shadows the
		// err variable declared above.
		b, err := strconv.ParseBool(s)
		if err != nil {
			return 0, err
		}

		// If execution goes here, some new gophers
		// might expect a nil error will be returned.
		// But in fact, the outer non-nil error will
		// be returned instead, for the scope of the
		// inner err variable ends at the end of the
		// outer if-clause.
		if b {
			n = 1
		}
	}
	return n, err
}

func main() {
	fmt.Println(parseInt("TRUE"))
}
</code></pre>
<p></p>
<div class="tmd-usual">
The output:
</div>
<p></p>
<pre class="tmd-code output">
1 strconv.Atoi: parsing "TRUE": invalid syntax
</pre>
<p></p>
<p></p>
<div id="weird-shadowing" class="tmd-usual">
Go only has <a href="keywords-and-identifiers.html#keyword">25 keywords</a>. Keywords can't be used as identifiers. Many familiar words in Go are not keywords, such as <code class="tmd-code-span">int</code>, <code class="tmd-code-span">bool</code>, <code class="tmd-code-span">string</code>, <code class="tmd-code-span">len</code>, <code class="tmd-code-span">cap</code>, <code class="tmd-code-span">nil</code>, etc. They are just predeclared (built-in) identifiers. These predeclared identifiers are declared in the universe block, so custom declared identifiers can shadow them. Here is a weird example in which many predeclared identifiers are shadowed. Its compiles and runs okay.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import (
	"fmt"
)

// Shadows the built-in function identifier "len".
const len = 3
// Shadows the built-in const identifier "true".
var true = 0
// Shadows the built-in variable identifier "nil".
type nil struct {}
// Shadows the built-in type identifier "int".
func int(){}

func main() {
	fmt.Println("a weird program")
	var output = fmt.Println

	// Shadows the package import "fmt".
	var fmt = [len]nil{{}, {}, {}}
	// Sorry, "len" is a constant.
	// var n = len(fmt)
	// Use the built-in cap function instead, :(
	var n = cap(fmt)

	// The "for" keyword is followed by one
	// implicit local code block and one explicit
	// local code block. The iteration variable
	// "true" shadows the package-level variable
	// "true" declared above.
	for true := 0; true &lt; n; true++ {
		// Shadows the built-in const "false".
		var false = fmt[true]
		// The new declared "true" variable
		// shadows the iteration variable "true".
		var true = true+1
		// Sorry, "fmt" is an array, not a package.
		// fmt.Println(true, false)
		output(true, false)
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
The output:
</div>
<pre class="tmd-code output">
a weird program
1 {}
2 {}
3 {}
</pre>
<p></p>
<div class="tmd-usual">
Yes, this example is extreme. It contains many bad practices. Identifier shadowing is useful, but please don't abuse it.
</div>
<p></p>
</div>
